package com.lwj.framework.security.auth;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import com.lwj.framework.entity.AuthProperties;

/**
 * 支持redis存储的jwt构造器
 *
 * @author lwj
 *
 */
public class JwtRedisAccessTokenConverter extends JwtAccessTokenConverter {
	static final Logger logger = LoggerFactory.getLogger(JwtRedisAccessTokenConverter.class);
	AuthProperties authProperties;

	public JwtRedisAccessTokenConverter(AuthProperties authProperties) {
		this.authProperties = authProperties;
	}

	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		if (accessToken instanceof DefaultOAuth2AccessToken) {
			DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) accessToken;
			try {
				final Map<String, Object> additionalInformation = new HashMap<String, Object>();
				if (OAuthUtils.isStore(authentication, authProperties)) {
					additionalInformation.put(OAuthUtils.isStore, OAuthUtils.True);
				}
				defaultOAuth2AccessToken.setAdditionalInformation(additionalInformation);
				OAuth2AccessToken enhancedToken = super.enhance(defaultOAuth2AccessToken, authentication);
				return enhancedToken;
			} catch (Exception e) {
				logger.error("parse tokenStore error", e);
				return accessToken;
			}
		} else {
			return accessToken;
		}
	}

}
